package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Product;
import cn.wolfcode.trip.base.query.ProductQueryObject;
import cn.wolfcode.trip.base.service.IProductService;
import cn.wolfcode.trip.base.service.IProductTypeService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductTypeService productTypeService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") ProductQueryObject qo, Model model) {
        qo.setOrderBy("addTime desc");
        PageInfo<Product> list = productService.queryProduct(qo);

        model.addAttribute("pageInfo", list);
        model.addAttribute("types" ,productTypeService.listAll());
        return "product/list";
    }

    @RequestMapping(value = "/getInfo", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object getContent(Long id) {
        return productService.getInfo(id);
    }
    @RequestMapping("/changeState")
    @ResponseBody
    public Object changeState(Long id, Integer state) {
        productService.changeState(id, state);
        return new JSONResult();
    }

    @RequestMapping("/saveOrUpdate")

    public String saveOrUpdate(Product entity, MultipartFile img) {
        if (img != null && img.getContentType().startsWith("image") && img.getSize() > 0) {
            String url = UploadUtil.upload(img);
            entity.setProductImg(url);
        }
        productService.saveOrUpdate(entity);
        return "redirect:/product/list.do";
    }
    @RequestMapping(value = "/getInfoById", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getContentById(Long id) {
        return productService.getInfo(id);
    }

    @RequestMapping("/productDownList")
    public String productDownList(@ModelAttribute("qo") ProductQueryObject qo, Model model) {
        qo.setState(0);
        qo.setOrderBy("addTime desc");
        PageInfo<Product> list = productService.queryProduct(qo);
        model.addAttribute("pageInfo", list);
        return "product/productDownList";
    }



}
